<template>
	<div>
        <van-nav-bar
			title="修改密码"
			left-arrow
			left-text="返回"
			fixed
			@click-left="goBack"
		/>
        <van-form @submit="onChangePsw">
		<van-field
			v-model="oldPassword"
			clearable
			type="password"
			name="oldPassword"
			label="旧密码"
			placeholder="请填写旧密码"
			:rules="[{ required: false, message: '请填写旧密码' }]" 
		/>
        <van-field
			v-model="password"
			clearable
			type="password"
			name="password"
			label="新密码"
			placeholder="请输入新密码"
			:rules="[{ required: true, message: '请输入新密码' }]" 
		/>
		<van-field
			v-model="ppassword"
			clearable
			type="password"
			name="ppassword"
			label="确认新密码"
			placeholder="请再次输入新密码"
			:rules="[{ required: true, message: '请再次输入新密码' }]" 
		/>
        <div style="margin: 16px;">
			<van-button round block type="info" native-type="submit">修改密码</van-button>
		</div>
        </van-form>
	</div>
</template>

<script>
	import {changePsw} from '../../api/person.js';
    import { Toast } from 'vant';
	export default {
		name: 'settings',
		data() {
			return {
                oldPassword: '',   //  旧密码
                password: '',   //  新密码
                ppassword: ''  //  再次输入的密码
			}
		},
		methods:{
			onChangePsw() {  // 修改密码
                if(this.password === this.ppassword) {
                    changePsw({
                        "newPassword": this.password,
                        "oldPassword": this.oldPassword
                    }).then(res => {
                        console.log(res);
                        if(res.data.code === 0) {
                            
                            Toast.loading({
                                message: '加载中...',
                                forbidClick: true,
                            });
                            const timer = setInterval(() => {
                                this.$router.push({
									name: 'home',
									params: {
										active: 1
									}
								})					
                                Toast('修改密码成功');
                                clearInterval(timer);
                            }, 2000);
                            
                        } else if(res.data.code === 1007){
                            Toast('原密码错误');
                            
                        } else {
                            Toast(res.data.msg);
                            
                        }
                        
                    }).catch(err => {
                        console.log(err);
                    });
                } else {
                    Toast('您输入的两次密码不同');
                }	
			},
			goBack() {
				this.$router.push({
					name: 'home',
					params: {
						active: 1
					}
				})
			}
		}
	}
</script>

<style>
</style>
